<?php
namespace Biz\model;

use Doraemon\pockets\datebase\BaseDbModel;

class ShopGoodsPool extends BaseDbModel
{

	const _CONFIG_FILE_ = 'db_shop';

	const _CONFIG_SELECT_ = 'db_shop';

	const _DATABASE_ = 'shop';

	const _TABLE_NAME = 'shop_goods_pool';

	const STATUS_NORMAL  = 1;
	const STATUS_DEL  = 9;

	const PAGE_SIZE = 20;

	public static function admPoolList($id ,$page, $pagesize = self::PAGE_SIZE)
	{
		$where = [
			'status' => self::STATUS_NORMAL,
			'LIMIT' => [($page - 1) * $pagesize, $pagesize],
			'ORDER' => ['create_time' =>  'DESC']
		];
		if ($id)  $where = array_merge(['id' => $id], $where);
		$list = self::select('*', $where);

		$list = array_map(function ($v) {

			$v['goods_count'] = count(explode( ',', $v['goods_ids']));

			return $v;
		}, $list);

		return [
			'list' => $list,
			'total' => self::count([
				'status' => self::STATUS_NORMAL
			])
		];
	}

	public static function admSaveData($data, $id = 0)
	{
		$data['edit_time'] = date('Y-m-d H:i:s');
		if (!$id) $data['create_time'] = date('Y-m-d H:i:s');
		if (!$data['title'] || !$data['goods_ids']) {
			throw new \Exception('标题或商品不允许为空');
		}
		if ($id) {
			$rst = self::update($data, ['id' => $id]);
			return $rst -> rowCount();
		} else {
			self::insert($data);
			return self::id();
		}
	}

	public static function admDel($id, $adminUid) {
		return self::update(['status' => self::STATUS_DEL, 'edit_time' => date('Y-m-d H:i:s'), 'admin_uid' => $adminUid], ['id' => $id]) -> rowCount();
	}

	public static function getById($poolId) {
		return self::get('*', [
			'id' => $poolId,
			'status' => self::STATUS_NORMAL
		]);
	}

}